package com.feiyuan.common.utils;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    /**
     * get请求-params传参
     * @param url
     * @param params
     * @param headParams
     * @return
     */
    public static String doHttpGet(String url, Map<String,String> params, Map<String,String> headParams) {
        String result = null;
        //1.获取httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //接口返回结果
        CloseableHttpResponse response = null;
        String paramStr = null;
        try {
            List<BasicNameValuePair> paramsList = new ArrayList<BasicNameValuePair>();

            if (params != null && !params.isEmpty()) {
                for (String key : params.keySet()) {
                    paramsList.add(new BasicNameValuePair(key, params.get(key)));
                }
            }
            paramStr = EntityUtils.toString(new UrlEncodedFormEntity(paramsList));
            //拼接参数
            StringBuffer sb = new StringBuffer();
            sb.append(url);
            sb.append("?");
            sb.append(paramStr);

            //2.创建get请求
            HttpGet httpGet = new HttpGet(sb.toString());
            //3.设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(5000).build();
            httpGet.setConfig(requestConfig);
            /*此处可以添加一些请求头信息，例如：
            httpGet.addHeader("content-type","text/xml");*/
            if (headParams != null && !headParams.isEmpty()) {
                for (String head : headParams.keySet()) {
                    httpGet.addHeader(head, headParams.get(head));
                }
            }
            //4.提交参数
            response = httpClient.execute(httpGet);
            //5.得到响应信息
            int statusCode = response.getStatusLine().getStatusCode();
            //6.判断响应信息是否正确
            if (HttpStatus.SC_OK != statusCode) {
                //终止并抛出异常
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            //7.转换成实体类
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity);
            }
            EntityUtils.consume(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //8.关闭所有资源连接
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * post请求-params传参
     */
    public static String doPost(String url, Map<String,String> params, Map<String,String> headParams) {
        String result = null;
        //1. 获取httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            //2. 创建post请求
            HttpPost httpPost = new HttpPost(url);

            //3.设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
            httpPost.setConfig(requestConfig);

            //4.提交参数发送请求
            List<BasicNameValuePair> paramsList = new ArrayList<>();
            if (params != null && !params.isEmpty()) {
                for (String key : params.keySet()) {
                    paramsList.add(new BasicNameValuePair(key,params.get(key)));
                }
            }
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paramsList, HTTP.UTF_8);
            httpPost.setEntity(urlEncodedFormEntity);
            if (headParams != null && !headParams.isEmpty()) {
                //设置请求头
                for (String head : headParams.keySet()) {
                    httpPost.addHeader(head, headParams.get(head));
                }
            }

            response = httpClient.execute(httpPost);

            //5.得到响应信息
            int statusCode = response.getStatusLine().getStatusCode();
            //6. 判断响应信息是否正确
            if (HttpStatus.SC_OK != statusCode) {
                //结束请求并抛出异常
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            //7. 转换成实体类
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //8. 关闭所有资源连接
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * post请求-body传参
     * @param url
     * @param params
     * @param headParams
     * @return
     */
    public static String doPostJson(String url, String params,Map<String,String> headParams) {
        String result = null;
        //1. 获取httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            //2. 创建post请求
            HttpPost httpPost = new HttpPost(url);

            //3.设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
            httpPost.setConfig(requestConfig);

            //4.提交参数发送请求
            httpPost.setEntity(new StringEntity(params, ContentType.create("application/json", "utf-8")));

            if (headParams != null && !headParams.isEmpty()) {
                //设置请求头
                for (String head : headParams.keySet()) {
                    httpPost.addHeader(head, headParams.get(head));
                }
            }

            response = httpClient.execute(httpPost);

            //5.得到响应信息
            int statusCode = response.getStatusLine().getStatusCode();
            //6. 判断响应信息是否正确
            if (HttpStatus.SC_OK != statusCode) {
                //结束请求并抛出异常
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            //7. 转换成实体类
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //8. 关闭所有资源连接
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 获取重定向后的地址
     * @param url 原地址
     */
    public static String getRedirectUrl(String url, String referer) {
        try {
            HttpClient httpClient = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build();
            HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url))
                                        .GET()
                                        .header("Accept", "*/*")
                                        .header("Accept-Encoding", "identity;q=1, *;q=0")
                                        .header("Accept-Language", "zh,en-GB;q=0.9,en;q=0.8")
                                        .header("Range", "bytes=0-")
//                                        .header("Referer", "http://www.78497.com/")
                                        .header("Referer", referer)
                                        .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36")
                                        .build();
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            int statusCode = response.statusCode();
            logger.info("this is url 【{}】 is statusCode:{}", url, statusCode);
            if (statusCode == 404) {
                // 如果得到的结果为404的话,返回404,并重新获取地址
                logger.info("this is url 【{}】 statusCode is 404!", url);
                return "404";
            }
            URI uri = response.uri();
            String path = uri.toString();
            logger.info("获取到的重定向的地址为:{}", path);
            return path;
        } catch (IOException | InterruptedException e) {
            logger.error("获取重定向地址出错了，错误信息为:{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
//        String str = doHttpGet("https://v12.fentvoss.com/sdv12/202407/09/089JHrcWu28/video/index.m3u8", null, null);
//        System.out.println("===========" + str);
//        str = str.replace("#EXTM3U", "").replace("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=132,RESOLUTION=1280x536", "").replaceAll("\\s+", "");
//        System.out.println("===========" + str);
//        String url = "https://y80s.net/movie/search/";
//        Map<String, String> params = new HashMap<>();
//        params.put("search_typeid", "1");
//        params.put("skey", "九部的检察官");
//        params.put("Input", "搜索");
//        String doPost = HttpClientUtils.doPost(url, params, null);
//        System.out.println(doPost);

//        String getUrl = "https://y80s.net/ju/9046/hd-2";
//        String httpGet = HttpClientUtils.doHttpGet(getUrl, null, null);
//        System.out.println(httpGet);
//        Map<String,String> params = new HashMap<>();
//        params.put("id", "512837");
//        params.put("quality", "320");
//        String httpGet = doHttpGet("http://api.wxmp3.com/url.php", null, null);
//        System.out.println("===========" + httpGet);

//        test("http://js.eev3.com/mp3/bb2759c850804cb32a55480d85d21080.mp3");
    }

}
